import request from '@/utils/request'
import type { ApiResponse } from '@/types/customer'

// 定义分页响应类型
interface PaginatedResponse<T> {
  list: T[]
  total: number
  page: number
  limit: number
}

// 订单类型定义
interface Order {
  id: number
  order_no: string
  customer_name: string
  total_amount: number
  paid_amount: number
  approval_status: number
  create_time: number
}

// 财务记录类型
interface FinanceRecord {
  id: number
  received_amount: number
  payment_type: number
  payment_method: number
  verification_status: number
  received_date: string
  payer_name: string
  remark: string
}

// 统计数据类型
interface FinanceStats {
  pending_orders: number
  pending_records: number
  this_month_amount: number
}

// 查询参数类型
interface FinanceQueryParams {
  page?: number
  limit?: number
  customer_name?: string
}

// 创建财务记录数据
interface FinanceRecordData {
  order_id: number
  payment_type: number
  received_amount: number
  received_date: string
  payment_method: number
  payer_name: string
  remark?: string
}

export const financeApi = {
  // 获取待审核订单列表
  getPendingOrders: (
    params: FinanceQueryParams
  ): Promise<ApiResponse<PaginatedResponse<Order>>> => {
    return request({
      url: '/api/crm/finance/pendingOrders',
      method: 'get',
      params,
    })
  },

  // 获取财务统计数据
  getFinanceStats: (): Promise<ApiResponse<FinanceStats>> => {
    return request({
      url: '/api/crm/finance/stats',
      method: 'get',
    })
  },

  // 获取财务记录列表
  getFinanceRecords: (orderId: number): Promise<ApiResponse<{ list: FinanceRecord[] }>> => {
    return request({
      url: `/api/crm/finance/records/${orderId}`,
      method: 'get',
    })
  },

  // 添加财务记录
  addFinanceRecord: (data: FinanceRecordData): Promise<ApiResponse<any>> => {
    return request({
      url: '/api/crm/finance/records',
      method: 'post',
      data,
    })
  },

  // 核实财务记录
  verifyFinanceRecord: (id: number): Promise<ApiResponse<any>> => {
    return request({
      url: `/api/crm/finance/records/verify/${id}`,
      method: 'post',
    })
  },

  // 删除财务记录
  deleteFinanceRecord: (id: number): Promise<ApiResponse<any>> => {
    return request({
      url: `/api/crm/finance/records/${id}`,
      method: 'delete',
    })
  },

  // 财务审核
  financeApproval: (orderId: number): Promise<ApiResponse<any>> => {
    return request({
      url: `/api/crm/finance/approval/${orderId}`,
      method: 'post',
    })
  },
}
